//
//  ChartTableViewCell.m
//  MyWallet
//
//  Created by 美鑫科技 on 16/8/9.
//  Copyright © 2016年 MorpLCP. All rights reserved.
//

#import "ChartTableViewCell.h"

@interface ChartTableViewCell ()

@property (nonatomic, strong) UILabel *lblTitle;
@property (nonatomic, strong) UIView *chartView;
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation ChartTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
        self.lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(5, 5,  [UIScreen mainScreen].bounds.size.width - 10, 30)];
        _lblTitle.textAlignment = NSTextAlignmentCenter;
        _lblTitle.font = [UIFont systemFontOfSize:15.0f];
        [self.contentView addSubview:_lblTitle];
        self.chartView = [[UIView alloc] initWithFrame:CGRectMake(0, 5 + _lblTitle.frame.size.height,  [UIScreen mainScreen].bounds.size.width, 200)];
        //        _chartView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3f];
        _chartView.backgroundColor = [UIColor clearColor];
        [self.contentView addSubview:_chartView];
        self.bottomView = [[UIView alloc] initWithFrame:CGRectMake(5, _chartView.frame.origin.y + _chartView.frame.size.height, _chartView.frame.size.width, 30)];
        [self.contentView addSubview:_bottomView];
    }
    return self;
}

- (void)setTitle:(NSString *)title
{
    _title = title;
    _lblTitle.text = title;
}

- (void)setChartType:(NSUInteger)chartType
{
    _chartType = chartType;
    if (self.chartView.subviews.count > 0)
    {
        [[self.chartView subviews].firstObject removeFromSuperview];
        [[self.chartView subviews].lastObject removeFromSuperview];
    }
    if (self.bottomView.subviews.count > 0)
    {
        [[self.bottomView subviews].firstObject removeFromSuperview];
    }
    if (chartType == 0)
    {
        [self strokLineChart];
    }
    else if (chartType == 1)
    {
        [self strokInComeBarChart];
    }
    else if (chartType == 2)
    {
        [self strokOutBarChart];
    }
    else if (chartType == 3)
    {
        [self strokInComePieChart];
    }
    else if (chartType == 4)
    {
        [self strokOutPieChart];
    }
}

// 绘制折线图
- (void)strokLineChart
{
    NSDictionary *dataDict = [[BillManager manager] getBillListWithCurrentMonth];
    NSMutableArray *keyArray =  [NSMutableArray array];
    NSMutableArray *tempKeyArray = dataDict.allKeys.mutableCopy;
    NSMutableArray *inComeValueArray = [NSMutableArray array];
    NSMutableArray *outValueArray = [NSMutableArray array];
    /*排序*/
    [tempKeyArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
     {
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];
         [formater setDateFormat:@"yyyy-MM-dd"];
         NSDate *date1 = [formater dateFromString:obj1];
         NSDate *date2 = [formater dateFromString:obj2];
         if ([[date1 earlierDate:date2] isEqual:date1]) return NSOrderedAscending;
         else return NSOrderedDescending;
     }];
    for (NSString *key in tempKeyArray)
    {
        NSString *simpleKey = [key substringWithRange:NSMakeRange(5, 5)];
        [keyArray addObject:simpleKey];
        NSString *inComeValue = [[BillManager manager] getConclusionWithDate:key];
        CGFloat inComeMoney = [inComeValue componentsSeparatedByString:@","].firstObject.floatValue;
        [inComeValueArray addObject:@(inComeMoney)];
        NSString *outValue = [[BillManager manager] getConclusionWithDate:key];
        CGFloat outMoney = [outValue componentsSeparatedByString:@","].lastObject.floatValue;
        [outValueArray addObject:@(outMoney)];
    }
    /*排序*/
    [keyArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
     {
         NSDateFormatter *formater = [[NSDateFormatter alloc] init];
         [formater setDateFormat:@"MM-dd"];
         NSDate *date1 = [formater dateFromString:obj1];
         NSDate *date2 = [formater dateFromString:obj2];
         if ([[date1 earlierDate:date2] isEqual:date1]) return NSOrderedAscending;
         else return NSOrderedDescending;
     }];
    PNLineChart *lineChartInCome = [[PNLineChart alloc] initWithFrame:CGRectMake(0, 0, self.chartView.frame.size.width , self.chartView.frame.size.height)];
    lineChartInCome.backgroundColor = [UIColor clearColor];
    lineChartInCome.showCoordinateAxis = YES;
    //    lineChartInCome.showSmoothLines = YES;
    [lineChartInCome setXLabels:keyArray];
    lineChartInCome.yGridLinesColor = [UIColor lightGrayColor];
    lineChartInCome.showYGridLines = YES;
    PNLineChartData *inComeLineData = [PNLineChartData new];
    inComeLineData.dataTitle = @"收入";
    inComeLineData.color = PNFreshGreen;
    inComeLineData.itemCount = lineChartInCome.xLabels.count;
    inComeLineData.inflexionPointColor = PNFreshGreen;
    inComeLineData.inflexionPointStyle = PNLineChartPointStyleCircle;
    inComeLineData.getData = ^(NSUInteger index)
    {
        CGFloat yValue = [inComeValueArray[index] floatValue];
        return [PNLineChartDataItem dataItemWithY:yValue];
    };
    PNLineChartData *outLineData = [PNLineChartData new];
    outLineData.dataTitle = @"支出";
    outLineData.color = PNRed;
    outLineData.itemCount = lineChartInCome.xLabels.count;
    outLineData.inflexionPointColor = PNRed;
    outLineData.inflexionPointStyle = PNLineChartPointStyleTriangle;
    outLineData.getData = ^(NSUInteger index)
    {
        CGFloat yValue = [outValueArray[index] floatValue];
        return [PNLineChartDataItem dataItemWithY:yValue];
    };
    lineChartInCome.legendStyle = PNLegendItemStyleSerial;
    lineChartInCome.legendFont = [UIFont systemFontOfSize:12.0f];
    lineChartInCome.chartData = @[inComeLineData, outLineData];
    [lineChartInCome strokeChart];
    UIView *legends = [lineChartInCome getLegendWithMaxWidth:300];
    [legends setFrame:CGRectMake(0, 5, self.bottomView.frame.size.width, self.bottomView.frame.size.height)];
    [self.bottomView addSubview:legends];
    [self.chartView addSubview:lineChartInCome];
}

// 绘制当前月份各方面收入情况柱状图
- (void)strokInComeBarChart
{
    // 准备数据
    NSDictionary *dataDict = [[BillManager manager] getBillListWithCurrentMonth];
    NSMutableArray *allInComeDataArray = [NSMutableArray array];
    NSMutableArray *xLableArray = [NSMutableArray array];
    NSMutableArray *yValueArray = [NSMutableArray array];
    // 合并每天的账单
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSString *key in dataDict)
    {
        [tempArray addObjectsFromArray:dataDict[key]];
    }
    // 装载收入账单数据
    for (Bill *bill in tempArray)
    {
        if (bill.bType == 1) {
            [allInComeDataArray addObject:bill];
            if ([xLableArray containsObject:bill.bUse])
            {
                continue;
            }
            [xLableArray addObject:bill.bUse]; // 收入类型数组
        }
    }
    if (xLableArray.count == 0)
    {
        UILabel *lblNoData = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.chartView.frame.size.height - 50) / 2.0, self.chartView.frame.size.width, 50)];
        lblNoData.textAlignment = NSTextAlignmentCenter;
        lblNoData.font = [UIFont systemFontOfSize:20];
        lblNoData.text = @"暂无数据";
        lblNoData.textColor = [UIColor lightGrayColor];
        [self.chartView addSubview:lblNoData];
        return;
    }
    for (NSString *use in xLableArray)
    {
        double money = 0.0;
        for (Bill *bill in allInComeDataArray)
        {
            if ([bill.bUse isEqualToString:use])
            {
                money += bill.bMoney;
            }
        }
        [yValueArray addObject:@(money)];
    }
    //    static NSNumberFormatter *barChartFormatter;
    //    if (!barChartFormatter){
    //        barChartFormatter = [[NSNumberFormatter alloc] init];
    //        barChartFormatter.numberStyle = NSNumberFormatterCurrencyStyle;
    //        barChartFormatter.allowsFloats = NO;
    //        barChartFormatter.maximumFractionDigits = 0;
    //    }
    PNBarChart *barChart = [[PNBarChart alloc] initWithFrame:CGRectMake(0, 0, self.chartView.frame.size.width , self.chartView.frame.size.height)];
    barChart.backgroundColor = [UIColor clearColor];
    //    barChart.yLabelFormatter = ^(CGFloat yValue) {
    //        return [barChartFormatter stringFromNumber:[NSNumber numberWithFloat:yValue]];
    //    };
    barChart.yChartLabelWidth = 20.0;
    barChart.chartMarginLeft = 30.0;
    barChart.chartMarginRight = 10.0;
    barChart.chartMarginTop = 5.0;
    barChart.chartMarginBottom = 10.0;
    barChart.labelMarginTop = 5.0;
    barChart.showChartBorder = YES;
    [barChart setXLabels:xLableArray];
    [barChart setYValues:yValueArray];
    [barChart strokeChart];
    [self.chartView addSubview:barChart];
}

// 绘制各月份支出情况柱状图
- (void)strokOutBarChart
{
    // 准备数据
    NSDictionary *dataDict = [[BillManager manager] getBillListWithCurrentMonth];
    NSMutableArray *allInComeDataArray = [NSMutableArray array];
    NSMutableArray *xLableArray = [NSMutableArray array];
    NSMutableArray *yValueArray = [NSMutableArray array];
    // 合并每天的账单
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSString *key in dataDict)
    {
        [tempArray addObjectsFromArray:dataDict[key]];
    }
    // 装载支出账单数据
    for (Bill *bill in tempArray)
    {
        if (bill.bType == 0)
        {
            [allInComeDataArray addObject:bill];
            if ([xLableArray containsObject:bill.bUse])
            {
                continue;
            }
            [xLableArray addObject:bill.bUse]; // 支出类型数组
        }
    }
    if (xLableArray.count == 0)
    {
        UILabel *lblNoData = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.chartView.frame.size.height - 50) / 2.0, self.chartView.frame.size.width, 50)];
        lblNoData.textAlignment = NSTextAlignmentCenter;
        lblNoData.font = [UIFont systemFontOfSize:20];
        lblNoData.text = @"暂无数据";
        lblNoData.textColor = [UIColor lightGrayColor];
        [self.chartView addSubview:lblNoData];
        return;
    }
    for (NSString *use in xLableArray)
    {
        double money = 0.0;
        for (Bill *bill in allInComeDataArray)
        {
            if ([bill.bUse isEqualToString:use])
            {
                money += bill.bMoney;
            }
        }
        [yValueArray addObject:@(money)];
    }
    PNBarChart *barChart = [[PNBarChart alloc] initWithFrame:CGRectMake(0, 0, self.chartView.frame.size.width , self.chartView.frame.size.height)];
    barChart.backgroundColor = [UIColor clearColor];
    barChart.yChartLabelWidth = 20.0;
    barChart.chartMarginLeft = 30.0;
    barChart.chartMarginRight = 10.0;
    barChart.chartMarginTop = 5.0;
    barChart.chartMarginBottom = 10.0;
    barChart.labelMarginTop = 5.0;
    barChart.showChartBorder = YES;
    [barChart setXLabels:xLableArray];
    [barChart setYValues:yValueArray];
    [barChart setStrokeColor:PNRed];
    [barChart strokeChart];
    [self.chartView addSubview:barChart];
}

// 饼状图 收入
- (void)strokInComePieChart
{
    // 准备数据
    NSDictionary *dataDict = [[BillManager manager] getBillListWithCurrentMonth];
    NSMutableArray *allInComeDataArray = [NSMutableArray array];
    NSMutableArray *xLableArray = [NSMutableArray array];
    NSMutableArray *yValueArray = [NSMutableArray array];
    // 合并每天的账单
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSString *key in dataDict)
    {
        [tempArray addObjectsFromArray:dataDict[key]];
    }
    // 装载收入账单数据
    for (Bill *bill in tempArray)
    {
        if (bill.bType == 1)
        {
            [allInComeDataArray addObject:bill];
            if ([xLableArray containsObject:bill.bUse])
            {
                continue;
            }
            [xLableArray addObject:bill.bUse]; // 收入类型数组
        }
    }
    if (xLableArray.count == 0)
    {
        UILabel *lblNoData = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.chartView.frame.size.height - 50) / 2.0, self.chartView.frame.size.width, 50)];
        lblNoData.textAlignment = NSTextAlignmentCenter;
        lblNoData.font = [UIFont systemFontOfSize:20];
        lblNoData.text = @"暂无数据";
        lblNoData.textColor = [UIColor lightGrayColor];
        [self.chartView addSubview:lblNoData];
        return;
    }
    for (NSString *use in xLableArray)
    {
        double money = 0.0;
        for (Bill *bill in allInComeDataArray)
        {
            if ([bill.bUse isEqualToString:use])
            {
                money += bill.bMoney;
            }
        }
        [yValueArray addObject:@(money)];
    }
    NSMutableArray *items = [NSMutableArray array];
    for (int i = 0; i < xLableArray.count; i++)
    {
        [items addObject:[PNPieChartDataItem dataItemWithValue:[yValueArray[i] floatValue] color:[self randomColor] description:xLableArray[i]]];
    }
    PNPieChart *pieChart = [[PNPieChart alloc] initWithFrame:CGRectMake((self.chartView.frame.size.width - 200) / 2.0 - 30, 0, 200 , 200) items:items];
    pieChart.descriptionTextColor = [UIColor whiteColor];
    pieChart.descriptionTextFont  = [UIFont fontWithName:@"Avenir-Medium" size:11.0];
    pieChart.descriptionTextShadowColor = [UIColor clearColor];
    pieChart.showAbsoluteValues = NO;
    pieChart.showOnlyValues = YES;
    [pieChart strokeChart];
    pieChart.legendStyle = PNLegendItemStyleStacked;
    pieChart.legendFont = [UIFont boldSystemFontOfSize:12.0f];
    UIView *legend = [pieChart getLegendWithMaxWidth:200];
    [legend setFrame:CGRectMake(pieChart.frame.origin.x + pieChart.frame.size.width + 5, 20, 80, self.chartView.frame.size.height - 20)];
    [self.chartView addSubview:legend];
    [self.chartView addSubview:pieChart];
}

- (UIColor *)randomColor
{
    int redRandom = arc4random_uniform(256);
    int greenRandom = arc4random_uniform(256);
    int blueRandom = arc4random_uniform(256);
    UIColor *color = [UIColor colorWithRed:redRandom / 255.0 green:greenRandom / 255.0 blue:blueRandom / 255.0 alpha:1];
    return color;
}

// 饼状图 支出
- (void)strokOutPieChart
{
    // 准备数据
    NSDictionary *dataDict = [[BillManager manager] getBillListWithCurrentMonth];
    NSMutableArray *allInComeDataArray = [NSMutableArray array];
    NSMutableArray *xLableArray = [NSMutableArray array];
    NSMutableArray *yValueArray = [NSMutableArray array];
    // 合并每天的账单
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSString *key in dataDict)
    {
        [tempArray addObjectsFromArray:dataDict[key]];
    }
    // 装载支出账单数据
    for (Bill *bill in tempArray)
    {
        if (bill.bType == 0)
        {
            [allInComeDataArray addObject:bill];
            if ([xLableArray containsObject:bill.bUse])
            {
                continue;
            }
            [xLableArray addObject:bill.bUse]; // 支出类型数组
        }
    }
    if (xLableArray.count == 0)
    {
        UILabel *lblNoData = [[UILabel alloc] initWithFrame:CGRectMake(0, (self.chartView.frame.size.height - 50) / 2.0, self.chartView.frame.size.width, 50)];
        lblNoData.textAlignment = NSTextAlignmentCenter;
        lblNoData.font = [UIFont systemFontOfSize:20];
        lblNoData.text = @"暂无数据";
        lblNoData.textColor = [UIColor lightGrayColor];
        [self.chartView addSubview:lblNoData];
        return;
    }
    for (NSString *use in xLableArray)
    {
        double money = 0.0;
        for (Bill *bill in allInComeDataArray)
        {
            if ([bill.bUse isEqualToString:use])
            {
                money += bill.bMoney;
            }
        }
        [yValueArray addObject:@(money)];
    }
    NSMutableArray *items = [NSMutableArray array];
    for (int i = 0; i < xLableArray.count; i++)
    {
        [items addObject:[PNPieChartDataItem dataItemWithValue:[yValueArray[i] floatValue] color:[self randomColor] description:xLableArray[i]]];
    }
    PNPieChart *pieChart = [[PNPieChart alloc] initWithFrame:CGRectMake((self.chartView.frame.size.width - 200) / 2.0 - 30, 0, 200 , 200) items:items];
    pieChart.descriptionTextColor = [UIColor whiteColor];
    pieChart.descriptionTextFont  = [UIFont fontWithName:@"Avenir-Medium" size:11.0];
    pieChart.descriptionTextShadowColor = [UIColor clearColor];
    pieChart.showAbsoluteValues = NO;
    pieChart.showOnlyValues = YES;
    [pieChart strokeChart];
    pieChart.legendStyle = PNLegendItemStyleStacked;
    pieChart.legendFont = [UIFont boldSystemFontOfSize:12.0f];
    UIView *legend = [pieChart getLegendWithMaxWidth:200];
    [legend setFrame:CGRectMake(pieChart.frame.origin.x + pieChart.frame.size.width + 5, 20, 80, self.chartView.frame.size.height - 20)];
    [self.chartView addSubview:legend];
    [self.chartView addSubview:pieChart];
}
//
//// 添加图表
//- (void)showChartView {
//
//    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"Budget_day"]) {
//        return;
//    }
//    double outMoney_day = [[[[BillManager manager] getConclusionWithDate:[FinalTools currentDateWithFormat:@"yyyy-MM-dd"]] componentsSeparatedByString:@","].lastObject doubleValue];
//    double budgetDay = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Budget_day"] doubleValue];
//
//    double outMoney_month = [[[[BillManager manager] getConclusion_Month_NoBlock] componentsSeparatedByString:@","].lastObject doubleValue];
//    double budgetMonth = [[[NSUserDefaults standardUserDefaults] objectForKey:@"Budget_month"] doubleValue];
//
//    PNCircleChart *circleChart_day = [[PNCircleChart alloc] initWithFrame:CGRectMake(0,0, self.chartView.frame.size.width / 2.0 - 2, self.chartView.frame.size.width / 2.0 - 2)
//                                                                    total:@(budgetDay)
//                                                                  current:@(outMoney_day)
//                                                                clockwise:YES];
//
//    circleChart_day.backgroundColor = [UIColor clearColor];
//
//    [circleChart_day setStrokeColor:[UIColor clearColor]];
//    [circleChart_day setStrokeColorGradientStart:[UIColor blueColor]];
//    [circleChart_day strokeChart];
//
//    [self.chartView addSubview:circleChart_day];
//
//    PNCircleChart *circleChart_month = [[PNCircleChart alloc] initWithFrame:CGRectMake(circleChart_day.frame.size.width + 4,0, self.chartView.frame.size.width / 2.0 - 2, self.chartView.frame.size.width / 2.0 - 2)
//                                                                      total:@(budgetMonth)
//                                                                    current:@(outMoney_month)
//                                                                  clockwise:YES];
//
//    circleChart_month.backgroundColor = [UIColor clearColor];
//
//    [circleChart_month setStrokeColor:[UIColor clearColor]];
//    [circleChart_month setStrokeColorGradientStart:[UIColor blueColor]];
//    [circleChart_month strokeChart];
//
//    [self.chartView addSubview:circleChart_month];
//
//}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
}

@end
